import { ImportOutlined, PlusOutlined } from "@ant-design/icons";
import { ActionType, ProColumns, ProTable } from "@ant-design/pro-components";
import { Button, Form, Input, message, Modal, Tag } from "antd"
import { useRef, useState } from "react";
import { documentCreate, documentDelete, documentList, documentUpdate } from "../api/request";
import { formatTime } from "../utils/utils";
import { useNavigate } from "react-router-dom";
import KnowledgeEdit from "./knowledge/components/KnowledgeEdit";
import ImportKnowledge from "./knowledge/components/ImportKnowledge";
import FileUpload from "../components/FileUpload";

type TableItem = {
    id: number;
    projectName: string;
    createdTime: string;
    count: number;
    updatedTime: string;
};

const layout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 18 },
};

export default () => {
    const actionRef = useRef<ActionType>();
    const [visibleCreate, setVisibleCreate] = useState(false);
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false)
    const [data, setData] = useState<TableItem>()
    const [type, setType] = useState<'create' | "update">('create')
    const [isKnowledgeEdit, setIsKnowledgeEdit] = useState(false);
    const [knowledgeType, setKnowledgeType] = useState<'create' | 'update'>('create');
    const [isImportKnowledge, setIsImportKnowledge] = useState(false);
    const [documentId, setDocumentId] = useState<number>()
    const navigate = useNavigate();
    const [exportMd, setExportMd] = useState(false)

    const columns: ProColumns<TableItem>[] = [
        {
            title: '名称',
            dataIndex: 'documentName',
            ellipsis: true,
            hidden: true,
        },
        {
            title: '名称',
            dataIndex: 'projectName',
            ellipsis: true,
            search: false,
            render: (text, record) => {
                return <Button type="link"
                    onClick={() => {
                        navigate(`/rag/knowledge`, {
                            state: {
                                id: record.id,
                            }
                        })
                    }}>{record.projectName}</Button>
            }
        },
        {
            title: '文档数量',
            dataIndex: 'count',
            width: 200,
            render: (dom, entity) => {
                return <Tag color="blue">{entity.count}</Tag>;
            }
        },
        {
            title: '修改时间',
            dataIndex: 'updatedTime',
            search: false,
            width: 230,
            render: (text, record) => {
                return formatTime(record.updatedTime as string)
            }
        },
        {
            title: '创建时间',
            dataIndex: 'createdTime',
            search: false,
            width: 230,
            render: (text, record) => {
                return formatTime(record.createdTime as string)
            }
        },
        {
            title: '操作',
            valueType: 'option',
            key: 'option',
            width: 230,
            render: (text, record, _, action) => [
                <Button type="link" style={{ padding: 0 }} onClick={() => {
                    setIsKnowledgeEdit(true)
                    setKnowledgeType('create')
                    setDocumentId(record.id)
                }}>
                    新建知识
                </Button>,
                <Button type="link" style={{ padding: 0 }} onClick={() => {
                    setData(record)
                    setVisibleCreate(true)
                    setType("update")
                    form.setFieldsValue({ documentName: record.projectName })
                }}>
                    修改
                </Button>,
                <Button type="link" style={{ padding: 0 }}
                    onClick={() => {
                        Modal.confirm({
                            title: '删除',
                            content: '是否删除',
                            onOk: async () => {
                                await documentDelete(record.id)
                                message.success("删除成功")
                                actionRef.current.reload()
                                Modal.destroyAll();
                            }
                        })
                    }}>
                    删除
                </Button>
            ],
        }
    ]

    return <>
        <ProTable<TableItem>
            columns={columns}
            headerTitle="知识库"
            actionRef={actionRef}
            cardBordered
            request={async (params) => await documentList(params.documentName) as any}
            editable={{
                type: 'multiple',
            }}
            rowKey="id"
            options={{
                setting: {
                    listsHeight: 400,
                },
            }}
            pagination={{
                pageSize: 5
            }}
            dateFormatter="string"
            toolBarRender={() => [
                <Button
                    key="button"
                    onClick={() => setIsImportKnowledge(true)}
                    type="primary"
                >
                    Web 站点
                </Button>,
                <Button
                    key="button"
                    onClick={() => setExportMd(true)}
                    icon={<ImportOutlined />}
                    type="primary"
                >
                    导入已有文本
                </Button>,
                <Button
                    key="button"
                    icon={<PlusOutlined />}
                    onClick={() => (setVisibleCreate(true), setType("create"), form.setFieldValue("documentName", ""))}
                    type="primary"
                >
                    新建知识库
                </Button>
            ]}
        />

        <KnowledgeEdit
            markdown={""}
            type={knowledgeType}
            open={isKnowledgeEdit}
            documentId={documentId}
            onChange={(open) => setIsKnowledgeEdit(open)}
            id={1}
            onOk={(open) => {
                actionRef.current?.reload()
                setIsKnowledgeEdit(open)
            }} />

        {/* 导入知识 */}
        <ImportKnowledge
            open={isImportKnowledge}
            onClose={() => setIsImportKnowledge(false)}
            onChange={(open) => {
                setIsImportKnowledge(open)
                actionRef.current?.reload()
            }} />

        <Modal title={type == "create" ? "新建" : "修改"}
            open={visibleCreate}
            onOk={() => {
                form.validateFields().then(async (values) => {
                    setLoading(true)
                    try {
                        if (type == "update") {
                            await documentUpdate(data.id, values.documentName)
                            message.success("修改成功")
                        } else {
                            await documentCreate(values.documentName)
                            message.success("创建成功")
                        }
                        setVisibleCreate(false)
                    } finally {
                        setLoading(false)
                        actionRef.current.reload()
                    }
                })
            }}
            confirmLoading={loading}
            onCancel={() => setVisibleCreate(false)}
            onClose={() => setVisibleCreate(false)}>
            <Form
                {...layout}
                form={form}
                style={{ maxWidth: 600 }}
            >
                <Form.Item name="documentName" label="名称" rules={[{ required: true }]}>
                    <Input autoComplete="off" />
                </Form.Item>
            </Form>
        </Modal>

        {/* 文件上传 */}
        <FileUpload open={exportMd} onClose={() => setExportMd(false)} />
    </>
}